
#import "NSString+VoiceOver.h"

@implementation NSString (VoiceOver)

-(NSString *)stringByOptimizingForVoiceOver
{
    __block NSString *buffer = [self stringByReplacingOccurrencesOfString:@"&ndash;" withString:@"–"];
    
    // "1%nbsp;000" -->  "1.000"
    NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:@"([0-9])(&nbsp;| )([0-9][0-9][0-9])" options:0 error:nil];
    buffer = [re stringByReplacingMatchesInString:buffer options:0 range:NSMakeRange(0, buffer.length) withTemplate:@"$1.$3"];
    
    // "700 - 1000" --> "700 till 1000"
    re = [NSRegularExpression regularExpressionWithPattern:@"([0-9]) *[-–] *([0-9])" options:0 error:nil];
    buffer = [re stringByReplacingMatchesInString:buffer options:0 range:NSMakeRange(0, buffer.length) withTemplate:@"$1 – $2"];
    buffer = [buffer stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    
    buffer = [buffer stringByReplacingOccurrencesOfString:@"–" withString:@"till"];

    NSDictionary *substitutions = @{@"V": @"volt",
                                    @"W": @"watt",
                                    @"kWh": @"kilowattimme",
                                    @"lm": @"lumen",
                                    @"K": @"kelvin",
                                    @"st": @"stycken",
                                    @"kr": @"kronor"};
    
    [substitutions enumerateKeysAndObjectsUsingBlock:^(NSString *abbr, NSString *word, BOOL *stop) {
        buffer = [buffer stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"(%@)", abbr] withString:@""];
        NSString *pattern = [NSString stringWithFormat:@" *\\b%@\\b|([0-9])%@\\b", abbr, abbr];
        NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
        buffer = [re stringByReplacingMatchesInString:buffer options:0 range:NSMakeRange(0, buffer.length) withTemplate:[@"$1 " stringByAppendingString:word]];
    }];

    // Remove texts with wrong information
    buffer = [buffer stringByReplacingOccurrencesOfString:@"<p><b>Dra regeln till önskad ljusstyrka. Välj ”Fortsätt”.</b>" withString:@""];

    return buffer;
}

@end
